#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDebug>
#include "widget2.h"
#include "ui_widget2.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &Widget::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &Widget::onReadyRead);
    connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &Widget::onError);

    socket->connectToHost("192.168.159.131", 1234);

    QLineEdit *lineEdit = ui->mima2;
    if (lineEdit) {
        lineEdit->setEchoMode(QLineEdit::Password);
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_zhuce_clicked() {
    QString username = ui->yonghuming2->text();
    QString password = ui->mima2->text();

    // 向服务器发送注册信息
    QString message = "REGISTER\n";
    message += username + "\n" + password + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";

}

void Widget::on_denglu_clicked() {
    QString username = ui->yonghuming2->text();
    QString password = ui->mima2->text();

    // 向服务器发送登录信息
    QString message = "LOGIN\n";
    message += username + "\n" + password + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";

}

void Widget::onConnected() {
    qDebug() << "已连接到服务器！";
}

void Widget::onReadyRead() {
    QByteArray data = socket->readAll();
    QDataStream stream(&data, QIODevice::ReadOnly);

    QString responseType;
    stream >> responseType;
    qDebug() << "接收信息";

    if (responseType == "REGISTER_SUCCESS") {
        QMessageBox::information(this, "提示", "注册成功");
    } else if (responseType == "REGISTER_FAIL") {
        QMessageBox::warning(this, "提示", "该用户名已被注册");
    } else if (responseType == "LOGIN_SUCCESS") {
        QString username = ui->yonghuming2->text();
        // 登录成功，进入新界面
        widget2 *newWidget = new widget2(username);  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
        this->close();  // 关闭当前窗口
    } else if (responseType == "LOGIN_FAIL") {
        QMessageBox::warning(this, "提示", "登录失败");
    }
}

void Widget::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}
